package org.scisaga.tetra.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONStringer;

public class Connector {
	ArrayList<String> hostList;
	HashMap<String, Float> replyList = new HashMap<String, Float>();

	public Connector(ArrayList<String> list) {
		hostList = list;
	}

	public Connector(JSONArray list) {
		hostList = new ArrayList<String>();
		for (int i = 0; i < list.length(); i++) {
			try {
				hostList.add(list.getString(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public HashMap<String, Float> exec() {

		for (String hostName : hostList) {
			String task = null;
			UUID id = UUID.randomUUID();
			try {
				task = new JSONStringer().object().key("id").value(
						id.toString()).key("type").value("TestServ")
						.endObject().toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// test the hostName if is reachable
			// TODO: Should test if the host is running a copy of Tetra Compute
			// Node

			Socket sock;
			
			long duration = 0;
			try {
				SocketAddress socketAddress = new InetSocketAddress(hostName, 12357);
				sock = new Socket();
				sock.connect(socketAddress, 1000);
				sock.setSoTimeout(1000);
				
				BufferedReader is = new BufferedReader(new InputStreamReader(
						sock.getInputStream(), "8859_1"));
				OutputStreamWriter osw = new OutputStreamWriter(sock
						.getOutputStream(), "8859_1");

				long startTime = System.currentTimeMillis();
				for (int i = 0; i < 20; i++) {

					osw.write(task + "\r\n");
					osw.flush();
					if (is.readLine() != "") {

					}

				}
				duration = System.currentTimeMillis() - startTime;
				sock.close();
			} catch (UnknownHostException e) {
				duration = 1000000;
				//e.printStackTrace();
			} catch (IOException e) {
				duration = 1000000;
				//e.printStackTrace();
			}
			replyList.put(hostName, (float) duration / 1000);
		}
		return replyList;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<String> list = new ArrayList<String>();
		list.add("166.111.59.15");
		list.add("166.111.59.28");
		list.add("211.157.108.23");
		Connector conr = new Connector(list);
		log(conr.exec());
	}

	public static void log(String s) {
		System.out.println(s);
	}

	public static void log(HashMap<String, Float> map) {
		for (String key : map.keySet()) {
			System.out.println(key + " -> " + map.get(key));
		}
	}
}
